package controllers

import (
	"ginstart/models/mysql"
	"ginstart/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func UserLogin(c *gin.Context) {
	tel := c.PostForm("tel")
	password := c.PostForm("password")
	users, err := mysql.Login(tel)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"response": JsonRes{
				Code:    500,
				Message: "登录失败，用户不存在",
				Data:    nil,
			},
		})
		return
	}
	if users.ID == 0 {
		c.JSON(http.StatusOK, gin.H{
			"response": JsonRes{
				Code:    500,
				Message: "登录失败，用户不存在",
				Data:    nil,
			},
		})
		return
	}
	if users.Password != pkg.Md5(password) {
		c.JSON(http.StatusOK, gin.H{
			"response": JsonRes{
				Code:    500,
				Message: "登录失败，密码错误",
				Data:    nil,
			},
		})
		return
	}
	handler, _ := pkg.TokenHandler(strconv.Itoa(int(users.ID)))
	c.JSON(http.StatusOK, gin.H{
		"response": JsonRes{
			Code:    200,
			Message: "成功",
			Data:    handler,
		},
	})
	return
}
